package me.thinkjet.sso.server.authentication;

import me.thinkjet.service.UserServiceImpl;
import me.thinkjet.sso.server.Credentials;
import me.thinkjet.sso.server.authentication.exception.AuthenticationException;
import me.thinkjet.sso.server.authentication.exception.BadCredentialsAuthenticationException;
import me.thinkjet.sso.server.authentication.exception.BadPasswordAuthenticationException;
import me.thinkjet.sso.server.authentication.exception.BadUsernameOrPasswordAuthenticationException;
import me.thinkjet.sso.server.authentication.exception.BlockedCredentialsAuthenticationException;
import me.thinkjet.sso.server.authentication.exception.UnknownUsernameAuthenticationException;
import me.thinkjet.sso.server.service.UserService;
import me.thinkjet.sso.server.utils.StringUtils;

import com.jfinal.plugin.activerecord.Model;

/**
 * 
 * @ClassName AuthenticationHandler
 * @author johnny_zyc
 * @Modified 2013-3-2 下午2:46:51
 * 
 */
public final class AuthenticationHandler {
	@SuppressWarnings("rawtypes")
	UserService userService = new UserServiceImpl();

	public AuthenticationHandler() {
	}

	public final boolean authenticate(final Credentials credentials)
			throws AuthenticationException {
		if (credentials == null) {
			throw new BadCredentialsAuthenticationException();
		}
		final String username = credentials.getName();
		final String password = credentials.getPassword();

		if (!(StringUtils.hasText(username) && StringUtils.hasText(password))) {
			throw new BadUsernameOrPasswordAuthenticationException();
		}
		@SuppressWarnings("rawtypes")
		Model m = userService.getUser(username);
		if (m == null) {
			throw new UnknownUsernameAuthenticationException();
		}
		if (!m.getBoolean(UserService.USER_ENABLE_FILED_NAME)) {
			throw new BlockedCredentialsAuthenticationException();
		}
		if (m.getStr(UserService.PASSWORD_FILED_NAME).equals(
				userService.getEncodedPassword(password))) {
			return true;
		} else {
			throw new BadPasswordAuthenticationException();
		}
	}
}
